/*
 * Copyright 2009-2010 by The Regents of the University of California
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * you may obtain a copy of the License from
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package edu.ucr.cs.dblab.acestore.base.datatypes;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.nio.ByteBuffer;

/**
 * @author jarodwen
 * @created May 29, 2011
 */
public class ShortSerDeserializer implements ISerDeserializer<Short> {

    private ShortSerDeserializer(){};
    
    private static class SingletonHolder {
        public static final ShortSerDeserializer INSTANCE = new ShortSerDeserializer();
    }
    
    public static ShortSerDeserializer getSingleton() {
        return SingletonHolder.INSTANCE;
    }
    
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

    }

    @Override
    public Short deserialize(ByteBuffer buf, int offset, int length)
            throws IOException {
        return deserialize(buf.array(), offset, length);
    }

    @Override
    public Short deserialize(byte[] buf, int offset, int length)
            throws IOException {
        return (short)(((buf[offset] & 0xff) << 8) + ((buf[offset + 1] & 0xff) << 0));
    }

    @Override
    public Short deserialize(DataInput in) throws IOException {
        return in.readShort();
    }

    @Override
    public Short deserialize(String str) throws IOException {
        return Short.valueOf(str);
    }

    @Override
    public byte[] serialize(Short data) throws IOException {
        return new byte[] {
                (byte)(data.shortValue() >>> 8),
                (byte)data.shortValue()
        };
    }

    @Override
    public byte[] serialize(String str) throws IOException {
        return serialize(Short.valueOf(str));
    }

    @Override
    public void serialize(Short data, DataOutput out) throws IOException {
        out.writeShort(data.shortValue());
    }

    @Override
    public int getTypeIndex() {
        return 2;
    }

    @Override
    public int getTypeSize() {
        return Short.SIZE / 8;
    }

    @Override
    public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2)
            throws IOException {
        short v1 = deserialize(b1, s1, l1);
        short v2 = deserialize(b2, s2, l2);
        return compare(v1, v2);
    }

    @Override
    public int compare(Short value1, Short value2) {
        return value1.compareTo(value2);
    }

}
